package edu.cth.stud.accelerateit.view.android;

import java.beans.PropertyChangeEvent;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import edu.cth.stud.accelerateit.R;
import edu.cth.stud.accelerateit.view.GUIController;

public class CorrectAWordActivity extends Activity implements
		IAndroidGUIComponent {

	private Button goBackButton;
	private Button correctButton;
	private EditText searchWordTF;
	private TextView definitionText;
	private TextView typeInText;
	private LinearLayout cawScreen;
	
	private InputFilter[] lettersInputFilters = new InputFilter[2];
	private TextWatcher textWatcher;
	
	private static String PREFS_NAME = "WordFinderSettings";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// creating the input filter in a separate method, for code structure:
		createInputFilters();
		
		// create the text change listener in a separate method, for code
		// structure:
		createTextWatcher();
		
		// A separate link content method, for code structure:
		linkContent();
		
		// Load the settings that are made in options
		loadSettings();
		
		// Register this activity/view with the GUIController:
		GUIController.getInstance().registerListener(this);
	}
	
	private void createTextWatcher() {
		// TODO: find the requirement that says the search button may only be
		// enabled when information has been entered and copy its ID here.
		textWatcher = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// Not needed as of now.
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// Not needed as of now.
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.length() == 0) {
					correctButton.setEnabled(false);
				} else {
					correctButton.setEnabled(true);
				}
			}
		};
		
	}

	private void createInputFilters() {
		// First, we create the letters-only filter:
		InputFilter letterFilter = new InputFilter() {
			public CharSequence filter(CharSequence source, int start, int end,
					android.text.Spanned dest, int dstart, int dend) {
				for (int i = start; i < end; i++) {
					if (!Character.isLetter(source.charAt(i))) {
						return "";
					}
				}
				return null;
			}
		};
		
		// Then we create a lengthfilter to keep away retardedly long inputs: 
		InputFilter lengthFilter = new InputFilter.LengthFilter(50);
		
		lettersInputFilters[0] = letterFilter;
		lettersInputFilters[1] = lengthFilter;
	}

	private void loadSettings(){
		
		SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
		cawScreen.setBackgroundColor(settings.getInt("backgroundColor", Color.BLACK));
		definitionText.setTextColor(settings.getInt("textColor", Color.WHITE));
		typeInText.setTextColor(settings.getInt("textColor", Color.WHITE));
	}

	private void linkContent() {
		// Set the content view to res\layout\caw_view.xml:
		setContentView(R.layout.caw_view);
		
		this.cawScreen = (LinearLayout) this.findViewById(R.id.cawScreen);
		this.goBackButton = (Button) findViewById(R.id.caw_goBackButton);
		this.searchWordTF = (EditText) this
				.findViewById(R.id.caw_searchWordTextField);
		this.correctButton = (Button) findViewById(R.id.button1);
		this.definitionText = (TextView) findViewById(R.id.caw_definitionText);
		this.typeInText = (TextView) findViewById(R.id.caw_TypeInText);
		
		// Give the text input field some censorship:
		searchWordTF.addTextChangedListener(textWatcher);
		searchWordTF.setFilters(lettersInputFilters);
		searchWordTF.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
		
		
		this.goBackButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				goBack();
			}
		});

		this.correctButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doSearch();
			}
		});
	}

	private void goBack() {
		// Required to keep down the activity count:
		finish();
		GUIController.getInstance().unregisterListener(this);

		Intent showMainMenu = new Intent(this.getApplicationContext(),
				WordFinderActivity.class);
		startActivity(showMainMenu);
	}

	/**
	 * This method is entered when the device's user hits the "back" button.
	 * 
	 * TODO: if the back button is pressed in any non-main-menu screen, the
	 * application is to behave in a certain way. Find the requirement ID for
	 * this and enter it here in this comment field.
	 */
	@Override
	public void onBackPressed() {
		goBack();
	}

	@Override
	public void propertyChange(PropertyChangeEvent event) {
		// If the event was a definition search result:
		if (event.getPropertyName().equals("DefinitionSearchResult")) {

			// Unwrapping the boolean:
			Boolean definitionExists = new Boolean(event.getNewValue()
					.toString());

			if (definitionExists) {
				definitionText.setText("That is a word!");
			} else {
				definitionText.setText("That is not a word!");
			}
		}

		// If the event was an application state message:
		else if (event.getPropertyName().equals("Last definition search term")) {
			searchWordTF.setText((String) event.getNewValue());
		}

		// If the event was a shutdown command:
		else if (event.getPropertyName().equals("Shutdown")) {
			GUIController.getInstance().unregisterListener(this);
			finish();
		}
	}

	public void doSearch() {
		String searchTerm = searchWordTF.getText().toString().toLowerCase();
		GUIController.getInstance().enterWordDefinitionSearch(searchTerm);
	}
}